program ss
character*200 str,fgrd,ftxt
integer m,n,na
integer bf_left,bf_right,bf_top,bf_bottom
real xmin,xmax,zmin,zmax,ymin,ymax
real,allocatable::den(:,:),dden(:,:)

na=iargc()

if(na.ge.6) then
  call getarg(1,fgrd)
  call getarg(2,ftxt)
  
    call getarg(3,str) 
  read(str,*) bf_left
    call getarg(4,str) 
  read(str,*) bf_right
    call getarg(5,str) 
  read(str,*) bf_top
    call getarg(6,str) 
  read(str,*) bf_bottom
else
  write(*,*) 'error '
  stop
endif
write(*,*) 'start calculation ...'
call grd_mn_sub(fgrd,m,n) 
     allocate(den(m,n),dden(m+1,n+1))
call grd_region_sub(fgrd,xmin,xmax,zmin,zmax,ymin,ymax)
call grd_dat_sub(fgrd,m,n,den)
call den2dden(m,n,den,dden,bf_left,bf_right,bf_top,bf_bottom)
!call mat_out_sub('mat',m,n,den)
call txt_out_sub(ftxt,m,n,xmin,xmax,zmin,zmax,dden)
write(*,*) 'calculation finished !'
deallocate(den,dden)
end program
!------------------------------------------------------------------
subroutine txt_out_sub(ftxt,nz,nx,xmin,xmax,zmin,zmax,dden)
character*(*) ftxt
integer nx,nz,nut
real xmin,xmax,zmin,zmax
real x,z,dx,dz
real dden(nz+1,nx+1)

dx=(xmax-xmin)/(nx-1)
dz=(zmax-zmin)/(nz-1)

call open_or_not(nut)
open(nut,file=ftxt)
do ix=1,nx+1
do jz=1,nz+1
  if(abs(dden(jz,ix)).gt.0.0)then
    x=xmin+(ix-1.5)*dx
    z=zmin+(jz-1.5)*dz
    write(nut,*) x,z,dden(jz,ix)
  endif
enddo
enddo
close(nut)

end subroutine
!------------------------------------------------------------------
subroutine mat_out_sub(fmat,m,n,den)
character*(*) fmat
character*5000 str
integer m,n,nut
real den(m,n)
call open_or_not(nut)
open(nut,file=fmat)
do i=1,m
  write(str,*) (den(i,j),j=1,n)
  write(nut,*) trim(str)
enddo
close(nut)
end subroutine
